//
//  HMHomePictureView.swift
//  Weibo
//
//  Created by Apple on 2017/7/15.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

//  每项的间距
let ItemMargin: CGFloat = 5
//  每个配图的宽度
let ItemWidth = (ScreenWidth - 2 * HomeCellMargin - 2 * ItemMargin) / 3

//  首页配图视图
class HMHomePictureView: UICollectionView {
    
    //  MARK:   --懒加载控件
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 20)
        label.textColor = UIColor.red
        return label
    }()
    
    //  配图数据源
    var picUrls: [HMHomePicture]? {
        didSet {
            messageLabel.text = "\(picUrls?.count ?? 0)"
            calcSize(count: picUrls?.count ?? 0)
            //  数据源改变重新加载数据
            reloadData()
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        flowLayout.minimumLineSpacing = ItemMargin
        flowLayout.minimumInteritemSpacing = ItemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        //  注册cell
        register(HMHomePictureViewCell.self, forCellWithReuseIdentifier: HomePictureCellIdentifier)
        //  设置代理
        dataSource = self
        delegate = self
        addSubview(messageLabel)
        messageLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    
    //  根据图片的个数计算配图的大小
    private func calcSize(count: Int) {
        
        if count == 1 {
            //  单张图片使用下载图片的大小作为配图的大小
            if let imageUrl = picUrls?.first?.thumbnail_pic {
                if let loadImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl) {
                    
                    var imageSize = loadImage.size
                    
                    if imageSize.width < 80 {
                        let currentWidth: CGFloat = 80
                        var currentHeight = currentWidth / imageSize.width * imageSize.height
                        if currentHeight > 150 {
                            currentHeight = 150
                        }
                        //  重新计算合适的大小
                        imageSize = CGSize(width: currentWidth, height: currentHeight)
                    }
                    
                    //  更新配图大小约束
                    self.snp.updateConstraints({ (make) in
                        make.size.equalTo(imageSize).priority(.high)
                    })
                    
                    //  重新更新item
                    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                    flowLayout.itemSize = imageSize
                }
                return
            }
            
        }
        
        //  计算显示的列数
        let cols = count > 3 ? 3 : count
        //  计算显示的行数
        let rows = (count - 1) / 3 + 1
        //  计算配图的宽度
        let currentWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMargin
        //  计算配图的高度
        let currentHeight = CGFloat(rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        //  计算配图大小
        let currentSize = CGSize(width: currentWidth, height: currentHeight)
        //  更新约束
        self.snp.updateConstraints { (make) in
            make.size.equalTo(currentSize).priority(.high)
        }
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
    }
}

//  MARK:   -- UICollectionViewDataSource 
extension HMHomePictureView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureCellIdentifier, for: indexPath) as! HMHomePictureViewCell
        cell.picture = picUrls![indexPath.item]
        
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    //  MARK:   --SDPhotoBrowserDelegate
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)
    }
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! HMHomePictureViewCell
        return cell.imageView.image
    }
}

//  首页配图cell
class HMHomePictureViewCell: UICollectionViewCell {
    
    //  MARK:   --懒加载控件
    fileprivate lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    var picture: HMHomePicture? {
        didSet {
            if let imageUrl = picture?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
                if imageUrl.hasSuffix(".gif") {
                    //  显示gif图片
                    gifImageView.isHidden = false
                } else {
                    //  隐藏gif图片
                    gifImageView.isHidden = true
                }
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  MARK:   --添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp.makeConstraints { (make) in
            make.bottom.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
}


